<template>
  <a-upload
      v-model:file-list="fileList"
      name="avatar"
      list-type="picture-card"
      class="avatar-uploader"
      :max-count="1"
      :customRequest="handleUpload"
      :before-upload="beforeUpload"
      @change="handleChange"
      @remove="remove"
      @preview="handlePreview"
  >
    <img :width="80" v-if="props.imgUrl !== '' && uploadTimes===0" :src="props.imgUrl" alt="avatar" />
    <div v-else>
      <loading-outlined v-if="loading"></loading-outlined>
      <plus-outlined v-else></plus-outlined>
      <div class="ant-upload-text">Upload</div>
    </div>
  </a-upload>
  <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>
<script setup>
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import {calculateBigFileMD5} from '@/utils/FileUtils.js'
import {uploadSingleWhole} from '@/api/UploadRequest.js'
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function getBase64Preview(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

const fileList = ref([]);
const loading = ref(false);
const imageUrl = ref('');
const emit = defineEmits(['get-instance']);
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const uploadTimes = ref(0);

const props = defineProps({
  imgUrl: {
    type: String,
    default: ''
  },
});

const handleChange = info => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    // Get this url from response in real world.
    getBase64(info.file.originFileObj, base64Url => {
      imageUrl.value = base64Url;
      props.imgUrl = base64Url;
      loading.value = false;
    });
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('上传失败！请联系管理员邮箱: heavenboy_pz@163.com');
  }
};
const beforeUpload = async file => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('必须上传 jpg/png 格式的图片');
  }
  const isLt2M = file.size / 1024 / 1024 < 10;
  if (!isLt2M) {
    message.error('图片大小不得超过10MB!');
  }
  return isJpgOrPng && isLt2M;
};

const handleUpload = async (data) => {
  console.log('handleUpload', data);
  const md5 = await calculateBigFileMD5(data.file);
  const fileName = data.file.name;
  const size = data.file.size;
  const file = data.file;

  const res = await uploadSingleWhole(md5, fileName, size, file);
  if(res.code === 0) {
    fileList.value[0].status = 'done';
    loading.value = false;
    emit('get-instance', {
      bucketName: res.data.bucketName,
      objectName: res.data.objectName,
    });
    uploadTimes.value += 1;
  } else {
    fileList.value[0].status = 'error';
    message.error(res.msg);
  }
}

const remove = (file) => {
  console.log('remove', file);
  emit('get-instance', {
    remove: true,
  });
  return true;
}

const handlePreview = async file => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64Preview(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};

</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>